package com.rxyb.authority.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rxyb.authority.constants.AuthorityConstants;
import com.rxyb.authority.db.dao.OpsAuthorityRoleMapper;
import com.rxyb.authority.db.po.OpsAuthorityMenu;
import com.rxyb.authority.db.po.OpsAuthorityRole;
import com.rxyb.authority.db.po.OpsAuthorityRoleMenu;
import com.rxyb.authority.gateway.dto.role.*;
import com.rxyb.authority.service.OpsAuthorityMenuService;
import com.rxyb.authority.service.OpsAuthorityRoleMenuService;
import com.rxyb.authority.service.OpsAuthorityRoleService;
import com.rxyb.core.respone.R;
import com.rxyb.core.respone.enums.CommonCode;
import com.rxyb.toolize.VO;
import com.rxyb.toolize.date.DateTime;
import com.rxyb.toolize.date.enums.FormatDate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author DUYH
 * @since 2020-05-29
 */
@Service
public class OpsAuthorityRoleServiceImpl extends ServiceImpl<OpsAuthorityRoleMapper, OpsAuthorityRole> implements OpsAuthorityRoleService {

    @Autowired(required = false)
    private OpsAuthorityRoleMapper opsAuthorityRoleMapper;
    @Autowired(required = false)
    private OpsAuthorityMenuService opsAuthorityMenuService;
    @Autowired(required = false)
    private OpsAuthorityRoleMenuService opsAuthorityRoleMenuService;

    /**
     * 创建
     *
     * @author duyh
     */
    @Override
    public R<CreateRoleRsp> create(CreateRoleReq createRoleReq) {
        if (VO.isNotBlank(createRoleReq.getRoleId())) {
            if (isExsit(createRoleReq.getRoleId())) {
                return R.failed(CommonCode.ROLE_HAS_EXSIT);
            }
        }
        OpsAuthorityRole record = new OpsAuthorityRole();
        BeanUtils.copyProperties(createRoleReq, record);
        record.setRowState(AuthorityConstants.ROWSTATE_NORMAL);
        record.setAddTime(DateTime.getDateTime());
        record.setUpdateTime(DateTime.getDateTime());
        // 该方法改为返回角色ID
        int cnt = opsAuthorityRoleMapper.insert(record);
        if (cnt == 1) {
            CreateRoleRsp createRoleRsp = new CreateRoleRsp();
            if (VO.isBlank(createRoleReq.getRoleId())) {
                // 如果roleId为空，则默认等于自增ID
                OpsAuthorityRole opsAuthorityRole = new OpsAuthorityRole();
                opsAuthorityRole.setId(record.getId());
                opsAuthorityRole.setRoleId(record.getId().toString());
                opsAuthorityRoleMapper.updateById(opsAuthorityRole);
                createRoleRsp.setRoleId(record.getId().toString());
            } else {
                createRoleRsp.setRoleId(createRoleReq.getRoleId());
            }
            createRoleRsp.setAddTime(DateTime.getDateFormat(record.getAddTime(), FormatDate.FORMAT_TIME_STR));
            return R.ok(createRoleRsp);
        }
        return R.failed(CommonCode.FAILED);
    }

    @Override
    public R<AuthRoleRsp> auth(AuthRoleReq authRoleReq) {
        // 校验角色是否存在
        QueryWrapper<OpsAuthorityRole> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(OpsAuthorityRole::getRoleId, authRoleReq.getRoleId()).eq(OpsAuthorityRole::getRowState, AuthorityConstants.ROWSTATE_NORMAL);
        OpsAuthorityRole opsAuthorityRole = opsAuthorityRoleMapper.selectOne(wrapper);
        if (null == opsAuthorityRole) {
            return R.failed(CommonCode.ROLE_NOT_EXIST);
        }
        boolean b = opsAuthorityRoleMenuService.update(authRoleReq.getRoleId(), authRoleReq.getMenuIds());
        if (b) {
            return R.ok(new AuthRoleRsp());
        }
        return R.failed(CommonCode.DB_ERROR);
    }

    /**
     * 详情
     *
     * @author duyh
     */
    @Override
    @Cacheable(cacheNames = {"role"}, key = "#getRoleInfoReq.getRoleId()", unless = "#result == null")
    public R<GetRoleInfoRsp> query(GetRoleInfoReq getRoleInfoReq) {
        QueryWrapper<OpsAuthorityRole> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(OpsAuthorityRole::getRoleId, getRoleInfoReq.getRoleId()).eq(OpsAuthorityRole::getRowState, AuthorityConstants.ROWSTATE_NORMAL);
        OpsAuthorityRole opsAuthorityRole = opsAuthorityRoleMapper.selectOne(wrapper);
        if (null == opsAuthorityRole) {
            return R.failed(CommonCode.ROLE_NOT_EXIST);
        }
        GetRoleInfoRsp getRoleInfoRsp = new GetRoleInfoRsp();
        BeanUtils.copyProperties(opsAuthorityRole, getRoleInfoRsp);
        getRoleInfoRsp.setAddTime(DateTime.getDateFormat(opsAuthorityRole.getAddTime(), FormatDate.FORMAT_TIME_STR));
        getRoleInfoRsp.setUpdateTime(DateTime.getDateFormat(opsAuthorityRole.getUpdateTime(), FormatDate.FORMAT_TIME_STR));
        return R.ok(getRoleInfoRsp);
    }

    /**
     * 修改
     *
     * @author duyh
     */
    @Override
    @CachePut(value = "role", key = "#updateRoleReq.getRoleId()")
    public R<UpdateRoleRsp> update(UpdateRoleReq updateRoleReq) {
        QueryWrapper<OpsAuthorityRole> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(OpsAuthorityRole::getRoleId, updateRoleReq.getRoleId()).eq(OpsAuthorityRole::getRowState, AuthorityConstants.ROWSTATE_NORMAL);
        // 需要修改的参数
        OpsAuthorityRole record = new OpsAuthorityRole();
        record.setRoleName(updateRoleReq.getRoleName());
        record.setRoleExt(updateRoleReq.getRoleExt());
        record.setRoleType(updateRoleReq.getRoleType());
        record.setOrgId(updateRoleReq.getOrgId());
        record.setUpdateTime(DateTime.getDateTime());
        int cnt = opsAuthorityRoleMapper.update(record, wrapper);
        if (cnt == 1) {
            return R.ok(new UpdateRoleRsp());
        }
        return R.failed(CommonCode.FAILED);
    }

    /**
     * 删除
     *
     * @author duyh
     */
    @Override
    @CacheEvict(value = "role", key = "#deleteRoleReq.getRoleId()")
    public R<DeleteRoleRsp> remove(DeleteRoleReq deleteRoleReq) {
        QueryWrapper<OpsAuthorityRole> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(OpsAuthorityRole::getRoleId, deleteRoleReq.getRoleId()).eq(OpsAuthorityRole::getRowState, AuthorityConstants.ROWSTATE_NORMAL);
        // 需要修改的参数
        OpsAuthorityRole record = new OpsAuthorityRole();
        record.setRowState(AuthorityConstants.ROWSTATE_DELETE);
        record.setUpdateTime(DateTime.getDateTime());
        // 修改的条件
        int cnt = opsAuthorityRoleMapper.update(record, wrapper);
        if (cnt == 1) {
            return R.ok(new DeleteRoleRsp());
        }
        return R.failed(CommonCode.FAILED);
    }

    /**
     * 列表
     *
     * @author duyh
     */
    @Override
    @Transactional(readOnly = true)
    public R<GetRoleListRsp> list(GetRoleListReq getRoleListReq) {
        GetRoleListRsp getRoleListRsp = new GetRoleListRsp();
        List<AuthorityRoleVo> resultList = new ArrayList<>();
        QueryWrapper<OpsAuthorityRole> wrapper = new QueryWrapper<>();
        /*根据菜单路径查询有权限的角色*/
        if (VO.isNotBlank(getRoleListReq.getMenuUrl())) {
            List<String> roleIds = queryRolesByMenu(getRoleListReq.getMenuUrl());
            if (roleIds == null || roleIds.size() == 0) {
                getRoleListRsp.setSize(0L);
                getRoleListRsp.setList(resultList);
                return R.ok(getRoleListRsp);
            }
            wrapper.lambda().in(OpsAuthorityRole::getRoleId, roleIds);
        }
        /*条件搜索*/
        if (AuthorityConstants.INVALID.toString().equals(getRoleListReq.getOrgId())) {
            wrapper.lambda().isNull(OpsAuthorityRole::getOrgId);
        } else if (VO.isNotBlank(getRoleListReq.getOrgId())) {
            wrapper.lambda().eq(OpsAuthorityRole::getOrgId, getRoleListReq.getOrgId());
        }
        if (null != getRoleListReq.getRoleType()) {
            wrapper.lambda().eq(OpsAuthorityRole::getRoleType, getRoleListReq.getRoleType());
        }
        if (VO.isNotBlank(getRoleListReq.getRoleName())) {
            wrapper.lambda().like(OpsAuthorityRole::getRoleName, "%" + getRoleListReq.getRoleName().trim() + "%");
        }
        wrapper.lambda().eq(OpsAuthorityRole::getRowState, AuthorityConstants.ROWSTATE_NORMAL);
        // 排序
        wrapper.orderByDesc("update_time");

        //总页数+总记录数
        Page<OpsAuthorityRole> page = new Page<>(getRoleListReq.getPageNo(), getRoleListReq.getPageSize());
        IPage<OpsAuthorityRole> iPage = opsAuthorityRoleMapper.selectPage(page, wrapper);
        List<OpsAuthorityRole> list = iPage.getRecords();
        if (list != null && list.size() != 0) {
            for (OpsAuthorityRole record : list) {
                AuthorityRoleVo role = new AuthorityRoleVo();
                BeanUtils.copyProperties(record, role);
                role.setAddTime(DateTime.getDateFormat(record.getAddTime(), FormatDate.FORMAT_TIME_STR));
                role.setUpdateTime(DateTime.getDateFormat(record.getUpdateTime(), FormatDate.FORMAT_TIME_STR));
                resultList.add(role);
            }
        }
        getRoleListRsp.setSize(iPage.getTotal());
        getRoleListRsp.setList(resultList);
        return R.ok(getRoleListRsp);
    }

    @Override
    @Cacheable(cacheNames = {"role"}, key = "#menuUrl", unless = "#result == null")
    public List<String> queryRolesByMenu(String menuUrl) {
        // 查询菜单信息
        final List<OpsAuthorityMenu> opsAuthorityMenus = opsAuthorityMenuService.queryMenusByUrl(menuUrl);
        if (null == opsAuthorityMenus || 0 == opsAuthorityMenus.size()) {
            return new ArrayList<>();
        }
        List<String> menuIds = opsAuthorityMenus.stream().map(OpsAuthorityMenu::getMenuId).distinct().collect(Collectors.toList());
        // 查询菜单对应的角色
        final List<OpsAuthorityRoleMenu> opsAuthorityRoleMenus = opsAuthorityRoleMenuService.queryRolesByMenu(menuIds);
        if (null == opsAuthorityRoleMenus || 0 == opsAuthorityRoleMenus.size()) {
            return new ArrayList<>();
        }
        final List<String> roleIds = opsAuthorityRoleMenus.stream().map(OpsAuthorityRoleMenu::getRoleId).distinct().collect(Collectors.toList());
        return roleIds;
        //        QueryWrapper<OpsAuthorityRole> wrapper = new QueryWrapper<>();
        //        wrapper.lambda().in(OpsAuthorityRole::getRoleId, roleIds).eq(OpsAuthorityRole::getRowState, AuthorityConstants.ROWSTATE_NORMAL);
        //        return opsAuthorityRoleMapper.selectList(wrapper);
    }

    /**
     * 角色ID是否存在
     */
    @Cacheable(cacheNames = {"role"}, key = "#roleId", unless = "#result == null")
    public boolean isExsit(String roleId) {
        QueryWrapper<OpsAuthorityRole> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(OpsAuthorityRole::getRoleId, roleId).eq(OpsAuthorityRole::getRowState, AuthorityConstants.ROWSTATE_NORMAL);
        List<OpsAuthorityRole> opsAuthorityRoles = opsAuthorityRoleMapper.selectList(wrapper);
        return opsAuthorityRoles.size() > 0;
    }

}
